#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowTitle("简单记事本");

    QMenuBar* menuBar = this->menuBar();
    QMenu* menu = new QMenu("文件");

    menuBar->addMenu(menu);

    QAction *action1 = new QAction("open");
    QAction *action2 = new QAction("save");
    menu->addAction(action1);
    menu->addAction(action2);

    edit = new QPlainTextEdit();
    QFont font;
    font.setPixelSize(20);
    edit->setFont(font);

    this->setCentralWidget(edit);

    connect(action1,&QAction::triggered,this,&MainWindow::openHandle);
    connect(action2,&QAction::triggered,this,&MainWindow::saveHandle);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::openHandle()
{
    QString path = QFileDialog::getOpenFileName(this);

    QStatusBar* statusBar = this->statusBar();
    statusBar->showMessage(path);

    QFile file(path);
    bool qOpen = file.open(QIODevice::ReadOnly);
    if(!qOpen)
    {
        statusBar->showMessage(path + "打开失败！");
        return;
    }

    QString text = file.readAll();

    file.close();

    edit->setPlainText(text);
}

void MainWindow::saveHandle()
{
    QString path = QFileDialog::getSaveFileName(this);

    QStatusBar* statusBar = this->statusBar();
    statusBar->showMessage(path);

    QFile file(path);
    bool qOpen = file.open(QIODevice::WriteOnly);
    if(!qOpen)
    {
        statusBar->showMessage(path + "打开失败！");
        return;
    }

    const QString& text = edit->toPlainText();
    file.write(text.toUtf8());

    file.close();
}

